import { Component,ViewChild,ElementRef,NgZone } from "@angular/core";
import { NavController,NavParams,AlertController,Content } from 'ionic-angular'
import { HttpClient,HttpHeaders } from '@angular/common/http'
import { NativeStorage } from '@ionic-native/native-storage';
import { LaunchNavigator } from '@ionic-native/launch-navigator';
import { PhotoViewer } from '@ionic-native/photo-viewer';
import { TranslateService } from '@ngx-translate/core';

import { PayPage } from "../../pay/pay";
import { ContactPage } from "../../contact/contact";
import { LookPage } from "../../contact/look/look";
import { HouseChoosePage } from "../houseChoose/houseChoose";

import { AppConfig } from '../../../app/app.config';
declare var google;
@Component({
    selector: 'page-product',
    templateUrl: 'buy.html',
})
export class ProductbuyPage {
    @ViewChild('map') mapElement: ElementRef;
    @ViewChild('fu') content_fu:Content;
    @ViewChild('zi') content_zi:Content;
    mapss:any;
    payPage =PayPage;
    contactPage =ContactPage;
    lookPage = LookPage;
    alert_active=false;
    report_active=false;
    video_active=false;
    info={
        logo:'',
        logos:'',
        full_logo:'',
        address:'',
        price_unit:'',
        price_type:1,
        price:'',
        deposit_unit:1,
        deposit_price:'',
        tax_unit:'',
        tax_price:'',
        floor:'',
        total_floor:'',
        owner_tel:'',
        description:'',
        owner_email:'',
        collect:true,
        video:'',
        autoorder:1,
    };
    url_pre:string;
    have_funish_options =[]
    evaluate_list=[]
    funish_options=[
        {
            id:1,
            ngclass:'iconfont icon-detail_sofa',
            text:'Sofa',
            checked:0,
        },
        {
            id:2,
            ngclass:'iconfont icon-detail_bed',
            text:'Bed',
            checked:0,
        },
        {
            id:3,
            ngclass:'iconfont icon-detail_TV',
            text:'TV',
            checked:0,
        },
        {
            id:4,
            ngclass:'iconfont icon-detail_air',
            text:'Air conditioning',
            checked:0,
        },
        {
            id:5,
            ngclass:'iconfont icon-detail_balcony',
            text:'Balcony',
            checked:0,
        },
        {
            id:6,
            ngclass:'iconfont icon-detail_boiler',
            text:'Boiler',
            checked:0,
        },
        {
            id:7,
            ngclass:'iconfont icon-post_wardrobe',
            text:'Sofa',
            checked:0,
        },
        {
            id:8,
            ngclass:'iconfont icon-detail_refrigerator',
            text:'Refrigerator',
            checked:0,
        },
        {
            id:9,
            ngclass:'iconfont icon-detail_heating',
            text:'Heating',
            checked:0,
        },
        {
            id:10,
            ngclass:'iconfont icon-detail_wash',
            text:'Washing machine',
            checked:0,
        },
        {
            id:11,
            ngclass:'iconfont icon-detail_garden',
            text:'Garden',
            checked:0,
        },
        {
            id:12,
            ngclass:'iconfont icon-detail_parking',
            text:'Parking',
            checked:0,
        },
    ]
    token=''
    latlng = []
    toCancat={}
    isRightIcon = true;
    constructor(
        private navCtl:NavController,
        private http: HttpClient,
        private navParams:NavParams,
        private alertCtrl:AlertController,
        private stroge:NativeStorage,
        private launchNavigator:LaunchNavigator,
        private photoViewer:PhotoViewer,
        private translate: TranslateService,
        private zone: NgZone
    ) {
        translate.setDefaultLang('en')
        this.url_pre = AppConfig.getMainUrl();
    }
    ionViewDidEnter(){
        this.stroge.getItem('lang').then(res=>{
          this.translate.use(res)
        })
    }
    isScrollToRight(){
        var a = this.content_fu.getContentDimensions().contentWidth,
        b = this.content_zi.getContentDimensions().contentLeft,
        c = this.content_zi.getContentDimensions().contentWidth;
        console.log(a+c+c);
        if(a+b>=c){
            this.zone.run(()=>{
                this.isRightIcon = false;
            })
            
        }
    }
    ngAfterViewInit() {
        let id = this.navParams.get('id');
        this.http.get(AppConfig.getUrl()+'house/info?id='+id).subscribe(res=>{
            if(res['code']==101){
                this.info = res['data']
                this.toCancat = res['data']
                if(res['data']['house_conf_ids']!=''){
                    this.have_funish_options = res['data']['house_conf_ids'].split(',')
                }
                setTimeout(() => { 
                    this.loadMap(res['data']['latitude'] ,res['data']['longitude']);
                },1000)
                this.latlng = [res['data']['latitude'],res['data']['longitude']]
            }
        })
        this.stroge.getItem('token').then(resp=>{
            this.token = resp
           
            this.http.get(AppConfig.getUrl()+'Cart/getComments?pid='+id+'&token='+resp+'&modal=house').subscribe(res=>{
                if(res['code']==101){
                    this.evaluate_list = res['data']
                }
            })
        })
    }
    show_title(){
        this.photoViewer.show(this.url_pre+this.info.logo, this.info.address, {share: false});
    }
    show_map(){
        this.photoViewer.show('https://maps.googleapis.com/maps/api/staticmap?center='+this.latlng[0]+','+this.latlng[1]+'&zoom=18&size='+window.innerHeight+'x'+window.innerHeight+'&key=AIzaSyBbZSA92ytChs7byM3SmEiF9wEisB2Wc78', this.info.address, {share: false});
    }
    show_street(){
        this.photoViewer.show('https://maps.googleapis.com/maps/api/streetview?size='+window.innerHeight+'x'+window.innerHeight+'&location='+this.latlng[0]+','+this.latlng[1]+'&heading=151.78&pitch=-0.76&key=AIzaSyBbZSA92ytChs7byM3SmEiF9wEisB2Wc78', this.info.address, {share: false});
    }
    show_floorplans(){
        this.photoViewer.show(this.url_pre+this.info.logos[0], this.info.address, {share: false});
    }
    show_shool() {
        
        this.alertb('','Please see below on map');
    }
    show_360(){
        this.photoViewer.show(this.url_pre+this.info.full_logo, this.info.address, {share: false});
    }
    gopay(){
        this.navCtl.push(HouseChoosePage,{data:this.toCancat})
        // if(this.info.autoorder == 1){
        //     this.navCtl.push(this.payPage,{data:this.toCancat})
        // }else if(this.info.autoorder == -1){
        //     this.navCtl.push(this.contactPage,{data:this.toCancat})
        // }
    }
        
    
    _type(item:number){
        switch(item){
            case 1:
                return 'month'
            case 2:
                return 'week'
            case 3:
                return 'day'
        }
    }
    _unit(item:number){
        switch(item){
            case 1:
                return '£'
            case 2:
                return '€'
            case 3:
                return '$'
            case 4:
                return '¥'
        }
    }
    _aunit(item:number){
        switch(item){
            case 1:
                return '㎡'
            case 2:
                return 'sq.ft'
        }
    }
    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    collect(){
        this.http.post(AppConfig.getUrl()+'house/collection?token='+this.token, AppConfig.urlEcode({pid:this.info['id']}),{headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) })
        .subscribe( (res) => {
            if(res['code']===101){
                this.info['collect'] = !this.info['collect']
            }else if(res['code']===202){
                this.alertb('Error!',res['msg']);
            }
        })
        event.stopPropagation();
    }
    loadMap(lat:number,lng:number) {
        let latLng = new google.maps.LatLng(lat, lng);
 
        let mapOptions = {
            center: latLng,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
    
        this.mapss = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
        let marker = new google.maps.Marker({
            map: this.mapss,
            animation: google.maps.Animation.DROP,
            position: this.mapss.getCenter()
        });
        var pyrmont = new google.maps.LatLng(this.latlng[0],this.latlng[1]);
        var request = {
          location: pyrmont,
          radius: '3000',
          query: 'university'
        };
      
        var service = new google.maps.places.PlacesService(this.mapss);
        service.textSearch(request, (results,status) => {
            if (status == google.maps.places.PlacesServiceStatus.OK) {
                for (let i = 0; i < results.length; i++) {
                  let place = results[i];
                  let marker = new google.maps.Marker({
                    position: new google.maps.LatLng(place.geometry.viewport.f.b,place.geometry.viewport.b.f),
                    title: place.name
                  });
                  let infowindow = new google.maps.InfoWindow({
                    content: place.name
                  });
                infowindow.open(this.mapss, marker);
                  marker.setMap(this.mapss);
                }
            }
        });
    }
    navto(){
        this.launchNavigator.navigate(this.latlng)
        .then(
            success => console.log('Launched navigator'),
            error => console.log('Error launching navigator', error)
        );
    }
    
   
}